import uos


def _mremovedirs(path, exclude: list = []):
    for i in uos.ilistdir(path):
        target_path = "{}/{}".format(path, i[0])

        if target_path in exclude:
            print("skip {}".format(target_path))
            exclude.remove(target_path)
            continue

        # 目录
        if (i[1] == 0x4000):
            _mremovedirs(target_path, exclude)

            if not uos.listdir(target_path):
                uos.rmdir(target_path)
                print("rmdir {}".format(target_path))

        # 文件
        elif (i[1] == 0x8000):
            uos.remove(target_path)
            print("remove {}".format(target_path))


def mremovedirs(path, exclude: list = []):
    '''清空指定目录下的所有文件及文件夹，排除列表请使用绝对路径'''
    if path == "/":
        path = ""

    for i in range(len(exclude)):
        try:
            if exclude[i][0] != "/":
                exclude[i] = "{}/{}".format(path, exclude[i])
        except:
            print("exclude error. {}".format(exclude[i]))

    if exclude:
        print("exclude: {}".format(exclude))

    _mremovedirs(path, exclude)


if __name__ == "__main__":
    # mremovedirs("/")
    # mremovedirs('/', ["/application.mpy", "checkcode.mpy", "/lib/logging.mpy"])
    pass
